﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

namespace Tesla.Graphics {
    /// <summary>
    /// Render bucket for transparent renderables. Transparent renderables are sorted
    /// back-to-front to achieve proper transparency. Transparent renderables
    /// with TransparencyType.OneSided are rendered as usual.
    /// 
    /// If a renderable's TransparencyType is TwoSided the renderable is rendered in two passes.
    /// The first pass renders the back faces and the second pass renders the front faces. The
    /// render states enforced during these passes can be overriden and
    /// their defaults are described below.
    /// 
    /// Renderables with a material that has more than one pass defines are
    /// rendered as usual, without any state enforcing, as they may
    /// not follow the above paradigm.
    /// </summary>
    public sealed class TransparentRenderBucket : RenderBucket {
        private RasterizerState _pass1RS;
        private DepthStencilState _pass1DSS;
        private RasterizerState _pass2RS;

        //Save the default pass1 RS state, so we don't have to recreate it again
        private RasterizerState _defaultPass1RS;

        /// <summary>
        /// Gets or sets the rasterizer state for rendering the back-faces
        /// of the geometry. Default is a state set to CullMode.Front and
        /// VertexWinding.CounterClockWise. Setting this null 
        /// sets the default state.
        /// </summary>
        public RasterizerState BackPassRasterizerState {
            get {
                return _pass1RS;
            }
            set {
                _pass1RS = value;
                if(value == null) {
                    _pass1RS = _defaultPass1RS;
                }
            }
        }

        /// <summary>
        /// Gets or sets the depth stencil state for rendering
        /// the back-faces of the geometry. Default is a state set to
        /// DepthWriteEnable = false. Setting this null sets the default state.
        /// </summary>
        public DepthStencilState BackPassDepthStencilState {
            get {
                return _pass1DSS;
            }
            set {
                _pass1DSS = value;
                if(value == null) {
                    _pass1DSS = DepthStencilState.DepthWriteOff;
                }
            }
        }

        /// <summary>
        /// Gets or sets the rasterizer state for rendering the front-faces
        /// of the geometry. Default is a state with CullMode.Back and
        /// VertexWinding.CounterClockWise. Setting this null sets the
        /// default state.
        /// </summary>
        public RasterizerState FrontPassRasterizerState {
            get {
                return _pass2RS;
            }
            set {
                _pass2RS = value;
                if(value == null) {
                    _pass2RS = RasterizerState.CullBackClockwiseFront;
                }
            }
        }

        /// <summary>
        /// Creates a new TransparentRenderBucket.
        /// </summary>
        /// <param name="renderer">Renderer to use</param>
        /// <param name="comparer">Renderable comparer to use</param>
        public TransparentRenderBucket(IRenderer renderer, IRenderBucketComparer comparer) 
            : base(renderer, comparer) {

        }

        //Will throw null if in constructor since when that's called we most likely have not yet set the render system provider...maybe
        //rethink that?
        private void Init() {
            if(_pass1RS == null) {
                _pass1RS = _defaultPass1RS = new RasterizerState();
                _pass1RS.Cull = CullMode.Front;
                _pass1RS.VertexWinding = VertexWinding.CounterClockwise;
                _pass1RS.BindRenderState();
            }

            if(_pass1DSS == null) {
                _pass1DSS = DepthStencilState.DepthWriteOff;
            }

            if(_pass2RS == null) {
                _pass2RS = RasterizerState.CullBackClockwiseFront;
            }
        }

        /// <summary>
        /// Renders all renderables in the bucket.
        /// </summary>
        public override void Render() {
            if(_defaultPass1RS == null) {
                Init();
            }
            for(int i = 0; i < Count; i++) {
                IRenderable renderable = this[i];
                if(renderable != null) {
                    TransparencyType type = renderable.TransparencyType;
                    //Account for a renderable with default type or if not a single-pass material
                    if(type == TransparencyType.Default || renderable.Material.PassCount != 1) {
                        type = TransparencyType.OneSided;
                    }

                    //If one sided, render as usual
                    if(renderable.TransparencyType == TransparencyType.OneSided) {
                        renderable.Render(Renderer);

                     //Otherwise, do the two-pass render
                    } else {
                        //See if we have an enforced RS state already.
                        RasterizerState oldEnRS = Renderer.EnforcedRasterizerState;

                        //Draw normally if we have an enforced state with CullMode none or FillMode wireframe,
                        //since these are probably meant to be enforced.
                        if(oldEnRS != null && (oldEnRS.Cull == CullMode.None || oldEnRS.Fill == FillMode.WireFrame)) {
                            renderable.Render(Renderer);
                            continue;
                        }

                        //Grab old enforced state if it exists too, so we can put these back afterwards.
                        DepthStencilState oldEnDSS = Renderer.EnforcedDepthStencilState;

                        //Enforce first pass states
                        Renderer.EnforcedDepthStencilState = _pass1DSS;
                        Renderer.EnforcedRasterizerState = _pass1RS;

                        //Render back faces
                        renderable.Render(Renderer);

                        //Enforce old DSS or clear
                        if(oldEnDSS != null) {
                            Renderer.EnforcedDepthStencilState = oldEnDSS;
                        } else {
                            Renderer.ClearEnforcedState(RenderStateType.DepthStencilState);
                        }

                        //Enforce second pass RS
                        Renderer.EnforcedRasterizerState = _pass2RS;

                        //Render front faces
                        renderable.Render(Renderer);

                        //Enforce old RS or clear
                        if(oldEnRS != null) {
                            Renderer.EnforcedRasterizerState = oldEnRS;
                        } else {
                            Renderer.ClearEnforcedState(RenderStateType.RasterizerState);
                        }
                    }
                }
            }
        }
    }
}
